#include <string.h>
#include <malloc.h>

#include "db_info.h"
#include "log.h"

static struct db_data *db_data_create(char *db_type_name, char *db_name, char *user_name, char *passwd, char *address)
{
	log_info("begin db_data_create.");

	if (db_type_name == NULL || db_name == NULL || user_name == NULL || passwd == NULL || address == NULL) {
		log_error("arg is NULL.");
		return NULL;
	}

	struct db_data *db_data = (struct db_data *)malloc(sizeof(struct db_data));
	if (db_data == NULL) {
		log_error("No enough mem.");
		return NULL;
	}

	strncpy(db_data->db_type_name, db_type_name, DB_TYPE_NAME_MAX_LEN);
	db_data->db_type_name[DB_TYPE_NAME_MAX_LEN] = '\0';

	strncpy(db_data->db_name, db_name, DB_NAME_MAX_LEN);
	db_data->db_name[DB_NAME_MAX_LEN] = '\0';

	strncpy(db_data->db_user_name, user_name, DB_USER_NAME_MAX_LEN);
	db_data->db_user_name[DB_USER_NAME_MAX_LEN] = '\0';

	strncpy(db_data->db_passwd, passwd, DB_PASSWD_MAX_LEN);
	db_data->db_passwd[DB_PASSWD_MAX_LEN] = '\0';

	strncpy(db_data->db_address, address, DB_ADDRESS_MAX_LEN);
	db_data->db_address[DB_ADDRESS_MAX_LEN] = '\0';

	db_data->next = NULL;

	pthread_mutex_init(&(db_data->lock), NULL);
	db_data->count = 0;

	db_data->alive = 1;

	return db_data;
}

struct db_info *db_info_create(void)
{
	log_info("begin db_info_create.");

	struct db_info *db_info = (struct db_info *)malloc(sizeof(struct db_info));
	if (db_info == NULL) {
		log_error("No enouth mem.");
		return NULL;
	}

	pthread_mutex_init(&(db_info->lock), NULL);
	db_info->count = 0;
	db_info->db_list_head = NULL;

	return db_info;
}

void add_db_data(struct db_info *db_info, char *db_type_name, char *db_name, char *user_name, char *passwd, char *address)
{
	log_info("begin add_db_data");

	if (db_info == NULL
		 || db_type_name == NULL
		 || db_name == NULL
		 || user_name == NULL
		 || passwd == NULL
		 || address == NULL) {
		log_error("arg is NULL.");
		return;
	}

	struct db_data *db_data = db_data_create(db_type_name, db_name, user_name, passwd, address);
	if (db_data == NULL) {
		log_error("cann't create db_data.");
		return;
	}
	
	pthread_mutex_lock(&(db_info->lock));
	
	if (db_info->count == 0) {
		db_info->db_list_head = db_data;
		db_info->count++;
	} else {
		struct db_data *tmp;
		for (tmp = db_info->db_list_head; tmp->next != NULL; tmp = tmp->next) {
			/* waitting... */
		}

		tmp->next = db_data;
		db_info->count++;
	}

	pthread_mutex_unlock(&(db_info->lock));
}
